<template>
  <div class="essay-page">
    <!-- 背景效果组件 -->
    <EssayBackground />

    <!-- 文章内容 -->
    <div class="essay-container">
      <!-- 加载、错误、空状态组件 -->
      <EssayStatus
        v-if="shouldShowStatus"
        :is-loading="isLoading"
        :api-error="apiError"
        :article-status="articleStatus"
        :essay-data="essayData"
        :ARTICLE_STATUS="ARTICLE_STATUS"
        @retry="fetchEssayData"
        @regenerate="handleArticle"
      />
      
      <!-- 内容区域 -->
      <div v-else class="content-area">
        <!-- Essay Content with Split View -->
        <div class="essay-content-container">
          <!-- Article Section (Left) -->
          <ArticleSection 
            ref="articleSectionRef"
            :width="leftWidth"
            :title="essayData.title"
            :paragraphs="essayData.paragraphs"
            :is-highlight-active="true"
            :vocabulary-words="essayData.wordList"
            :is-submitted="isFinished"
            :word-variations-map="wordVariationsMap"
            @word-status-change="handleWordStatusChange"
          />
          
          <!-- Resizer -->
          <Resizer @resize-start="startResize" />

          <!-- Questions Section (Right) -->
          <QuestionsSection 
            :width="100 - leftWidth"
            :questionModules="essayData.questionModules"
            :is-finished="isFinished"
            @submit="submitAnswers"
          />
        </div>
      </div>
    </div>
  </div>  
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getArticleDetail, submitArticleAnswers, regenerateArticle } from '@/api/article';
import { normalizeQuestionType } from '@/utils/answerUtils';
import { useModalStore } from '@/stores/modal';
import useWordHighlight, { WORD_STATUS } from '@/composables/useWordHighlight';

// 导入组件
import EssayBackground from './components/EssayBackground.vue';
import EssayStatus from './components/EssayStatus.vue';
import ArticleSection from '@/components/essay/ArticleSection.vue';
import Resizer from '@/components/essay/Resizer.vue';
import QuestionsSection from '@/components/essay/QuestionsSection.vue';

// 获取 modal store
const modalStore = useModalStore();

// 文章状态常量
const ARTICLE_STATUS = {
  UNKNOWN: 0,    // 未知状态
  GENERATING: 1, // 文章正在生成中
  ERROR: 2,      // 文章生成错误
  REGENERATING: 3, // 文章正在重新生成中
  COMPLETED: 4,  // 文章生成完成
  STUDIED: 5     // 文章已学习完成
};

// 获取状态描述
const getStatusDescription = (status) => {
  switch (status) {
    case ARTICLE_STATUS.GENERATING:
      return '文章生成中';
    case ARTICLE_STATUS.ERROR:
      return '文章生成错误';
    case ARTICLE_STATUS.REGENERATING:
      return '文章重新生成中';
    case ARTICLE_STATUS.COMPLETED:
      return '文章生成完成';
    case ARTICLE_STATUS.STUDIED:
      return '文章已学习完成';
    default:
      return '未知状态';
  }
};

const router = useRouter();
const route = useRoute();
const essayId = computed(() => route.params.id || '未知文章');
const isLoading = ref(true);
const apiError = ref(null);
const isFinished = ref(false);
const articleStatus = ref(ARTICLE_STATUS.UNKNOWN);
// 单词变形映射
const wordVariationsMap = ref({});

// 是否显示状态组件
const shouldShowStatus = computed(() => {
  return isLoading.value || 
         apiError.value || 
         articleStatus.value === ARTICLE_STATUS.GENERATING ||
         articleStatus.value === ARTICLE_STATUS.ERROR ||
         articleStatus.value === ARTICLE_STATUS.REGENERATING ||
         (!essayData.value.title && !isLoading.value);
});

// 用于控制API请求的状态
const isComponentMounted = ref(true);
const pollingTimerId = ref(null);
const isPolling = ref(false);

// 清除轮询定时器
const clearPollingTimer = () => {
  if (pollingTimerId.value) {
    clearTimeout(pollingTimerId.value);
    pollingTimerId.value = null;
  }
};

// 重新生成文章
const handleArticle = async () => {
  if (!isComponentMounted.value) return;
  
  // 防止重复点击
  if (isLoading.value) return;
  
  try {
    isLoading.value = true;
    clearPollingTimer();
    
    const articleId = extractArticleId(essayId.value);
    
    if (!articleId) {
      apiError.value = '无效的文章ID，无法重新生成';
      isLoading.value = false;
      return;
    }
    // 调用重新生成接口
    const response = await regenerateArticle({
      article_id: articleId
    });
    
    if (!isComponentMounted.value) return;
    
    if (response && response.code === 0) {
      // 更新状态为"文章正在重新生成"
      articleStatus.value = ARTICLE_STATUS.REGENERATING;
      apiError.value = null;
      // 启动轮询
      startPolling();
    } else {
      apiError.value = response?.msg || '重新生成请求失败';
    }
  } catch (error) {
    if (!isComponentMounted.value) return;
    apiError.value = '重新生成文章时发生错误，请稍后再试';
  } finally {
    if (isComponentMounted.value) {
      isLoading.value = false;
    }
  }
};

// 添加ref以访问ArticleSection组件
const articleSectionRef = ref(null);

// 使用单词高亮组合式API
const {
  wordList,
  updateWordList,
  updateWordStatus
} = useWordHighlight();

// 处理单词状态变化
const handleWordStatusChange = ({ word, status }) => {
  // 直接更新单词状态
  updateWordStatus(word, status);
};

// 获取单词的所有变形（包括原词）
const getAllWordVariations = (word) => {
  const lowerWord = word.toLowerCase();
  const variations = new Set([lowerWord]);
  
  // 遍历变形映射
  Object.entries(wordVariationsMap.value).forEach(([originalWord, variationsList]) => {
    const lowerOriginalWord = originalWord.toLowerCase();
    
    // 如果当前单词是原词，添加所有变形
    if (lowerOriginalWord === lowerWord) {
      variationsList.forEach(variation => {
        variations.add(variation.toLowerCase());
      });
    }
    
    // 如果当前单词是变形，添加原词和所有其他变形
    if (variationsList.some(v => v.toLowerCase() === lowerWord)) {
      variations.add(lowerOriginalWord);
      variationsList.forEach(v => {
        variations.add(v.toLowerCase());
      });
    }
  });
  
  return Array.from(variations);
};

// 修改submitAnswers函数，添加单词状态提交功能
const submitAnswers = async () => {
  if (!isComponentMounted.value) return;
  
  // 防止重复提交
  if (isLoading.value) return;
  
  try {
    // 首先检查高亮单词是否已全部标记
    if (!articleSectionRef.value.areAllWordsMarked()) {
      // 有未标记的高亮单词，提示用户并聚焦这些单词
      const unmarkedWords = articleSectionRef.value.focusUnmarkedWords();
      showToast('请标记文章中所有高亮的单词', 'error');
      console.log('未标记的高亮单词:', unmarkedWords);
      return; // 阻止提交
    }
    
    isLoading.value = true;
    const articleId = extractArticleId(essayId.value);
    if (!articleId) {
      return;
    }

    // 单词状态保存在essayData.wordList中
    showToast('单词状态已保存', 'info');
    
    // 调用API提交答案
    const response = await submitArticleAnswers(articleId);
    if (!isComponentMounted.value) return;
    
    if (response.code === 0) {
      // 提交成功，设置已完成状态，显示正确答案
      isFinished.value = true;
      
      // 重新获取文章详情，获取最新的答案状态
      await fetchEssayData();
    } else {
      // 提交失败，显示错误信息
      apiError.value = response.msg || '提交答案失败，请稍后重试';
    }
  } catch (error) {
    if (isComponentMounted.value) {
      console.error('提交答案时出错:', error);
      apiError.value = '提交答案时发生错误，请稍后重试';
    }
  } finally {
    if (isComponentMounted.value) {
      isLoading.value = false;
    }
  }
};

// 添加Toast提示函数
const showToast = (message, type = 'info') => {
  const toast = document.createElement('div');
  toast.className = `toast toast-${type}`;
  toast.style.position = 'fixed';
  toast.style.top = '20px';
  toast.style.left = '50%';
  toast.style.transform = 'translateX(-50%)';
  toast.style.padding = '10px 20px';
  toast.style.borderRadius = '4px';
  toast.style.backgroundColor = type === 'error' ? '#f44336' : '#333';
  toast.style.color = 'white';
  toast.style.zIndex = '9999';
  toast.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
  toast.textContent = message;
  
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 2500);
};

// 从essayId中提取文章ID
const extractArticleId = (id) => {
  // 如果ID格式为 "essay-2-1"，提取数字部分
  if (id.startsWith('essay-')) {
    return id.substring(6); // 返回 "2-1" 或其他ID
  }
  return id; // 如果没有前缀，直接返回
};

// 用于调整左右面板宽度的变量和函数
const leftWidth = ref(50); // 默认左侧宽度50%
let isResizing = false;

// 调整面板大小的函数
const startResize = (event) => {
  isResizing = true;

  // 添加事件监听器
  window.addEventListener('mousemove', handleResize);
  window.addEventListener('touchmove', handleResize);
  window.addEventListener('mouseup', stopResize);
  window.addEventListener('touchend', stopResize);
};

const handleResize = (event) => {
  if (!isResizing) return;

  // 获取容器宽度和鼠标/触摸位置
  const container = document.querySelector('.essay-content-container');
  if (!container) return;

  const containerRect = container.getBoundingClientRect();
  const containerWidth = containerRect.width;

  // 计算鼠标/触摸位置相对于容器的百分比
  let clientX;
  if (event.type === 'touchmove') {
    clientX = event.touches[0].clientX;
  } else {
    clientX = event.clientX;
  }

  const relativeX = clientX - containerRect.left;
  let newLeftWidth = (relativeX / containerWidth) * 100;

  // 限制最小和最大宽度
  newLeftWidth = Math.max(30, Math.min(70, newLeftWidth));

  // 更新左侧宽度
  leftWidth.value = newLeftWidth;
};

const stopResize = () => {
  isResizing = false;

  // 移除事件监听器
  window.removeEventListener('mousemove', handleResize);
  window.removeEventListener('touchmove', handleResize);
  window.removeEventListener('mouseup', stopResize);
  window.removeEventListener('touchend', stopResize);
};

// 启动轮询
const startPolling = () => {
  if (isPolling.value || !isComponentMounted.value) return;
  isPolling.value = true;
  // 确保先清除之前的定时器
  clearPollingTimer();
  
  pollingTimerId.value = setTimeout(async () => {
    if (!isComponentMounted.value) {
      isPolling.value = false;
      return;
    }
    
    try {
      isPolling.value = false;
      // 使用轻量级状态检查，而不是获取全部数据
      await checkArticleStatus();
    } catch (error) {
      console.error('轮询过程中出错:', error);
      
      if (isComponentMounted.value) {
        // 如果出错，延迟后重试
        pollingTimerId.value = setTimeout(() => {
          if (isComponentMounted.value) {
            startPolling();
          }
        }, 5000); // 出错后等待5秒再重试
      }
    }
  }, 3000);
};

// 轻量级状态检查函数 - 只获取文章状态，不获取完整内容
const checkArticleStatus = async () => {
  if (!isComponentMounted.value) return;
  
  try {
    const articleId = extractArticleId(essayId.value);
    
    if (!articleId) {
      apiError.value = '无效的文章ID';
      return;
    }
    
    // 调用API获取文章状态（使用status_only参数减少返回数据量）
    const response = await getArticleDetail(articleId, { status_only: true });
    
    if (!isComponentMounted.value) return;
    
    if (response.code === 0 && response.data) {
      const apiData = response.data;
      
      // 保存文章状态
      articleStatus.value = apiData.status || ARTICLE_STATUS.UNKNOWN;
      
      // 根据文章状态处理
      switch (apiData.status) {
        case ARTICLE_STATUS.COMPLETED:
        case ARTICLE_STATUS.STUDIED:
          // 文章已生成完成，获取完整内容
          await fetchEssayData();
          break;
          
        case ARTICLE_STATUS.GENERATING:
        case ARTICLE_STATUS.REGENERATING:
          // 文章仍在生成中，继续轮询
          startPolling();
          break;
          
        case ARTICLE_STATUS.ERROR:
          apiError.value = '文章生成失败，请尝试重新生成';
          break;
          
        default:
          apiError.value = `未知的文章状态: ${apiData.status}`;
          break;
      }
    } else {
      console.error('获取文章状态失败:', response.msg || '未知错误');
      apiError.value = response.msg || '获取文章状态失败，请稍后重试';
    }
  } catch (error) {
    console.error('检查文章状态时出错:', error);
    if (isComponentMounted.value) {
      apiError.value = '检查文章状态时发生错误，请稍后重试';
    }
  }
};

// 从API获取文章数据
const fetchEssayData = async () => {
  if (!isComponentMounted.value) return;
  
  clearPollingTimer();
  isLoading.value = true;
  apiError.value = null;
  
  try {
    const articleId = extractArticleId(essayId.value);
    
    if (!articleId) {
      apiError.value = '无效的文章ID';
      isLoading.value = false;
      return;
    }
    console.log('获取文章数据:', articleId);
    
    // 调用API获取文章详情
    const response = await getArticleDetail(articleId);
    
    if (!isComponentMounted.value) return;
    
    if (processApiResponse(response)) {
      console.log('成功获取文章数据');
    }
  } catch (error) {
    // API请求失败
    if (!isComponentMounted.value) return;
    
    console.error('获取文章时出错:', error);
    apiError.value = '获取文章时发生错误，请稍后重试';
  } finally {
    if (isComponentMounted.value) {
      isLoading.value = false;
    }
  }
};

// 处理API返回的数据
const processApiResponse = async (response) => {
  if (response.code === 0 && response.data) {
    const apiData = response.data;
    
    // 保存文章状态
    articleStatus.value = apiData.status || ARTICLE_STATUS.UNKNOWN;
    
    // 根据文章状态处理
    switch (apiData.status) {
      case ARTICLE_STATUS.COMPLETED:
      case ARTICLE_STATUS.STUDIED:
        try {
          await processArticleData(apiData);
        } catch (formatError) {
          handleDataFormatError(formatError);
        }
        break;
        
      case ARTICLE_STATUS.GENERATING:
      case ARTICLE_STATUS.REGENERATING:
        startPolling();
        break;
        
      case ARTICLE_STATUS.ERROR:
        apiError.value = '文章生成失败，请尝试重新生成';
        break;
        
      default:
        apiError.value = `未知的文章状态: ${apiData.status}`;
        break;
    }
    return true;
  } else {
    handleApiError(response);
    return false;
  }
};

// 处理API错误
const handleApiError = (response) => {
  console.error('获取文章失败:', response.msg || '未知错误');
  apiError.value = response.msg || '获取文章失败，请稍后重试';
};

// 处理数据格式错误
const handleDataFormatError = (error) => {
  console.error('文章数据格式错误:', error);
  apiError.value = '文章数据格式错误，请尝试重新生成';
  articleStatus.value = ARTICLE_STATUS.ERROR; // 设置为错误状态
};

// 处理文章数据
const processArticleData = async (apiData) => {
  // 获取单词列表
  let tempWordList = [];
  
  // 使用API返回的单词列表
  if (apiData.word_list && apiData.word_list.length > 0) {
    tempWordList = apiData.word_list;
  } 
  // 如果没有word_list，尝试使用words
  else if (apiData.words && apiData.words.length > 0) {
    tempWordList = apiData.words;
  }
  // 如果API没有返回单词列表，从文章中提取关键词
  else {
    tempWordList = extractKeywordsFromParagraphs(apiData.paragraphs);
  }
  
  // 更新单词变形映射
  if (apiData.word_map) {
    wordVariationsMap.value = apiData.word_map;
    console.log('单词变形映射:', wordVariationsMap.value);
  } else {
    // 如果API没有返回变形映射，使用空对象
    wordVariationsMap.value = {};
  }
  
  // 验证单词列表结构
  validateWordList(tempWordList);
  
  // 使用组合式API处理单词列表
  updateWordList(tempWordList);
  
  essayData.value = {
    title: apiData.title || '',
    paragraphs: Array.isArray(apiData.paragraphs) ? apiData.paragraphs : [],
    questionModules: formatQuestionsFromApi(apiData.questions || []),
    wordList: wordList.value // 使用处理后的单词列表
  };
  
  // 设置是否已完成状态
  isFinished.value = apiData.is_finished || apiData.status === ARTICLE_STATUS.STUDIED;
  
  console.log('成功获取文章数据，单词列表:', wordList.value.length, '个单词');
};

// 验证单词列表结构
const validateWordList = (wordList) => {
  if (!Array.isArray(wordList) || wordList.length === 0) {
    console.log('单词列表为空或不是数组');
    return;
  }
  
  console.log('验证单词列表结构，共', wordList.length, '个单词');
  
  // 检查单词结构
  wordList.forEach((word, index) => {
    // 检查是否缺少必要字段
    if (!word.content) {
      console.warn(`单词[${index}]缺少content字段:`, word);
    }
    
    // 检查状态字段
    if (!word.study_status) {
      console.warn(`单词[${index}] "${word.content}" 缺少study_status字段`);
      // 创建study_status对象
      word.study_status = {
        id: word.id || `word-${Math.random().toString(36).substring(2, 10)}`,
        status: WORD_STATUS.NORMAL
      };
    } else if (typeof word.study_status.status !== 'number') {
      console.warn(`单词[${index}] "${word.content}" 的study_status.status不是数字:`, word.study_status);
      // 设置默认状态
      word.study_status.status = WORD_STATUS.NORMAL;
    }
    
    // 确保主状态字段存在
    if (typeof word.status !== 'number') {
      console.warn(`单词[${index}] "${word.content}" 的status不是数字`);
      word.status = word.study_status.status || WORD_STATUS.NORMAL;
    }
  });
};

// 从段落中提取关键词
const extractKeywordsFromParagraphs = (paragraphs) => {
  if (!Array.isArray(paragraphs)) return [];
  
  const words = new Set();
  
  // 简单的单词提取逻辑，可以根据需要优化
  paragraphs.forEach(paragraph => {
    // 按空格和标点符号分割，提取单词
    const extractedWords = paragraph.match(/\b[A-Za-z]{4,}\b/g) || [];
    
    // 只保留长度大于等于4的单词，避免高亮太多常用词
    extractedWords.forEach(word => {
      if (word.length >= 4) {
        words.add(word.toLowerCase());
      }
    });
  });
  
  // 转换为数组并随机选择一部分单词（模拟课程单词）
  const wordsArray = Array.from(words);
  const selectedWords = [];
  
  // 随机选择10个单词或者全部单词（如果少于10个）
  const sampleSize = Math.min(10, wordsArray.length);
  const randomIndices = new Set();
  
  while (randomIndices.size < sampleSize) {
    const randomIndex = Math.floor(Math.random() * wordsArray.length);
    randomIndices.add(randomIndex);
  }
  
  randomIndices.forEach(index => {
    selectedWords.push({
      id: `word-${index}`,
      content: wordsArray[index],
      status: WORD_STATUS.NORMAL // 默认状态为NORMAL（灰色）
    });
  });
  
  return selectedWords;
};

// 将API返回的问题数据转换为组件需要的格式
const formatQuestionsFromApi = (apiQuestions) => {
  // 确保apiQuestions是数组
  if (!Array.isArray(apiQuestions)) {
    console.error('问题数据格式错误：不是数组', apiQuestions);
    return [];
  }
  
  try {
    // 按问题类型分组
    const questionsByType = apiQuestions.reduce((acc, q) => {
      // 跳过无效的问题数据
      if (!q || typeof q !== 'object') {
        console.warn('跳过无效的问题数据', q);
        return acc;
      }
      
      const type = q.type || 'unknown';
      
      if (!acc[type]) {
        acc[type] = [];
      }
      
      acc[type].push(q);
      return acc;
    }, {});
    
    // 转换为组件需要的格式
    return Object.entries(questionsByType).map(([type, questions]) => {
      try {
        // 标准化题型名称
        const normalizedType = normalizeQuestionType(type);
        
        // 创建题型模块
        return {
          type: normalizedType,
          data: {
            // 直接传递原始问题数据，让各组件自行处理
            questions: questions.map(q => ({
              ...q,
              id: q.id || `temp-${Math.random().toString(36).substring(2, 10)}`,
              text: q.text || q.content || '问题内容缺失',
              correctAnswer: q.correct_answer,
              is_correct: q.is_correct,
              user_answer: q.user_answer
            }))
          }
        };
      } catch (error) {
        return null;
      }
    }).filter(Boolean); // 过滤掉null值
  } catch (error) {
    return [];
  }
};

// 模拟文章和问题数据（作为备用）
const essayData = ref({
  title: "",
  paragraphs: [],
  questionModules: [],
  wordList: []
});

// 清理事件监听器和定时器
onBeforeUnmount(() => {
  // 标记组件已卸载
  isComponentMounted.value = false;
  
  // 清理resize事件监听器
  window.removeEventListener('mousemove', handleResize);
  window.removeEventListener('touchmove', handleResize);
  window.removeEventListener('mouseup', stopResize);
  window.removeEventListener('touchend', stopResize);
  
  // 清理定时器
  clearPollingTimer();
});

// 监听路由变化，如果路由改变，停止所有请求和轮询
watch(() => route.path, (newPath, oldPath) => {
  // 只有当路径真正改变且不再是当前文章页面时才清理
  if (newPath !== oldPath && !newPath.includes(`/essay/${essayId.value}`)) {
    isComponentMounted.value = false;
    clearPollingTimer();
  }
});

// 页面加载时初始化
onMounted(() => {
  isComponentMounted.value = true;
  // 自动收缩侧边栏
  modalStore.setSidebarVisible(false);
  
  // 初始化测试数据 - 仅在开发环境
  if (import.meta.env.DEV) {
    // 示例数据
    const testVariationsMap = {
      "decompose": ["decomposes", "decompose"],
      "ecology": ["ecological", "ecology"],
      "enzyme": ["enzymes"],
      "fluctuate": ["fluctuation", "fluctuations"],
      "herb": ["herbs"],
      "immense": ["immense"],
      "infringe": ["infringe"],
      "massive": [],
      "meadow": ["meadows"],
      "mechanism": ["mechanisms"],
      "organism": ["organisms"],
      "perish": ["perishes"],
      "plough": ["ploughing"],
      "preserve": ["preserving"],
      "rear": ["rearing"],
      "rot": ["rots"],
      "stack": ["stacking"],
      "stale": ["stale"],
      "undermine": ["undermine"],
      "vegetation": ["vegetation"]
    };
    
    // 注释掉以下行以禁用测试数据
    // wordVariationsMap.value = testVariationsMap;
    console.log('测试变形映射已准备好，取消注释以启用');
  }
  
  // 从后端加载文章和问题数据
  fetchEssayData();
});
</script>

<style scoped>
  .essay-page {
    @apply relative w-full bg-[#121212] text-white overflow-hidden min-h-screen;
  }
  
  /* Essay Container */
  .essay-container {
    @apply relative z-10 p-4 overflow-hidden touch-pan-y m-auto h-[94%] flex flex-col;
    -webkit-overflow-scrolling: touch;
  }
  
  /* Content Area */
  .content-area {
    @apply flex-1 flex flex-col w-full h-[calc(100vh-5rem)] overflow-hidden;
  }

  /* Essay Content with Split View */
  .essay-content-container {
    @apply flex flex-1 gap-0 overflow-hidden relative rounded-xl shadow-xl h-full;
    justify-content: space-between;
    transition: none;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .essay-content-container {
      @apply flex-col;
    }
  }
</style> 